<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Ajax请求控制器
 * @author [Eason] <[eason_1988@qq.com]>
 * @date(2016-03-29)
 */
class Ajax extends CI_Controller {
	
	/**
	 * 获取手机短信验证码
	 * @return bool
	 */
	public function getSMSCode()
	{
		$post = $this->input->post();
		if(!$post) jsonReturn(-1,'提交失败，请重新再试！');
		$type = isset($post['type'])?$post['type']:'reg';
		
		
		//验证用户是否注册
		if($type == 'reg'){
			$area =	trim($post['area']);//国别码
			$phone = trim($post['phone']);//手机号码
			$platform = $this->config->item('platform');
			if(!checkAreaisExists($area)) jsonReturn(-1,'获取验证码失败！');
			if(!regex($phone,'mobile')) jsonReturn(-1,'输入手机号码有误！');
			$this->load->model('user_model');
			$whereArr = array(
	        	'platform' => $platform,//平台
	        	'phone' => $phone,
	        );
			$isExist = $this->user_model->getUserInfoByMulti($whereArr);
			if($isExist) jsonReturn(-1,'此手机用户已经存在，请更换手机！');
		}else if($type == 'forgot'){
			$uid =	trim($post['uid']);//UID
			$this->load->model('user_model');
			$platform = $this->config->item('platform');//平台
	        $whereArr = array(
	            'platform' => $platform,//平台
	            'uid' => $uid,
	        );
	        $userData = $this->user_model->getUserInfoByMulti($whereArr);
	        if(empty($userData)){
	        	jsonReturn(-1,'发送失败1001！');
	        }
	        $area = $userData['area'];
	        $phone = $userData['phone'];
		}

		//链接redis
		$this->load->driver('cache');
		$this->cache->redis->is_supported();

		$smsKey = "$platform|AJAX|getSMSCode|$type|$area|$phone";
		$smsKeyCount = $smsKey."|Count";

		$cacheData = $this->cache->redis->get($smsKey);//已经获取过验证码
		if(!empty($cacheData)){
			$tmpArr = explode("|",$cacheData);
			if(time()<$tmpArr[1]){
				$data = array('expire'=>bcsub($tmpArr[1],time()));
				jsonReturn(1,'获取验证码太频繁！',$data);
			}
		}
		// $this->cache->redis->delete($smsKeyCount);
		//注册验证码获取次数不能一天不能超过5次
		$count = $this->cache->redis->get($smsKeyCount);
		if($count && $count >= 5) jsonReturn(-1,'注册验证码每天最多5次！');

		$expire	= 2*60;//按钮2分钟可以重新获取
		$code_expire = 5*60;//验证码5分钟过期
		$code = rand(1000,9999);//随机验证码
		$expire_time = time()+$expire;//过期时间

		if(sendSMS($area, $phone, $code)){
			$this->cache->redis->save($smsKey, "$code|$expire_time|$area|$phone", $code_expire);
			if($type == 'reg') {
				$this->cache->redis->increment($smsKeyCount);
				$this->cache->redis->expire($smsKeyCount,24*3600);
			}
			$data = array('expire'=>$expire);
			jsonReturn(0,"success",$data);
		}else{
			jsonReturn(-1,'发送失败！');
		}
	}


	public function getKlineData(){
		$get = $this->input->get();
		switch($get['type']){
			case 'XINA50':
				$symbol = "XINA50";
				$paramKey = 'HASH_XINA50_PARAM';
				break;
			case 'DAOUSD':
				$symbol = "DAOUSD";
				$paramKey = 'HASH_DAOUSD_PARAM';
				break;
			case 'XTIUSD':
				$symbol = "XTIUSD";
				$paramKey = 'HASH_XTIUSD_PARAM';
				break;
			case 'XAUUSD':
				$symbol = "XAUUSD";
				$paramKey = 'HASH_XAUUSD_PARAM';
				break;
			default:
				die('Request Error!');

		}
		// 连接Redis
		$redisClient = new Redis();
		$success = $redisClient->connect('120.27.159.11', 7480, 0);
		if (!$success){
			die('System Error!');
		}
		$redisClient->select(5);
		// 获取Redis 对象
        $param 	  = $redisClient->hgetall($paramKey);
		$from     = isset($get['from']) ? $get['from'] : -1000;
		$data     = $redisClient->lRange('LIST_KLINE_1MIN_'.$symbol.'_'.$param['m_contractMonth'], $from, -1);
		// 断开连接
		$redisClient->close();
		$arr = array();
		$jsonData = array();
		foreach ($data as $val) {
			$val    = explode(',', $val);
			$time = strtotime($val[0].' '.$val[1]).'000';
			if(in_array($time,$arr)){
				continue;
			}
			$arr[] = $time;
			$jsonData[] = array((float) $time,(float) $val[5]);
		}
		echo json_encode($jsonData);
		die();
	}


	public function getKlineData2(){
		$get = $this->input->get();
		switch($get['type']){
			case 'XINA50':
				$symbol = "XINA50";
				$paramKey = 'HASH_XINA50_PARAM';
				break;
			case 'DAOUSD':
				$symbol = "DAOUSD";
				$paramKey = 'HASH_DAOUSD_PARAM';
				break;
			case 'XTIUSD':
				$symbol = "XTIUSD";
				$paramKey = 'HASH_XTIUSD_PARAM';
				break;
			case 'XAUUSD':
				$symbol = "XAUUSD";
				$paramKey = 'HASH_XAUUSD_PARAM';
				break;
			default:
				die('Request Error!');

		}
		// 连接Redis
		$redisClient = new Redis();
		$success = $redisClient->connect('120.27.159.11', 7480, 0);
		if (!$success){
			die('System Error!');
		}
		$redisClient->select(5);
		// 获取Redis 对象
        $param 	  = $redisClient->hgetall($paramKey);
		$from     = isset($get['from']) ? $get['from'] : -100;
		$data     = $redisClient->lRange('LIST_KLINE_1MIN_'.$symbol.'_'.$param['m_contractMonth'], $from, -1);
		// 断开连接
		$redisClient->close();
		// ['2013/1/24', 2320.26,2320.26,2287.3,2362.94]
		// 数据意义：开盘(open)，收盘(close)，最低(lowest)，最高(highest)
		if(!empty($data)) foreach($data as $item){
			//2016-07-26,12:11:00,9492.5,9492.5,9492.5,9492.5,9,2,9492.5,False
			$tmpArr = explode(',',$item);
			$time = $tmpArr[0]." ".$tmpArr[1];
			$O = $tmpArr[2];
			$H = $tmpArr[3];
			$L = $tmpArr[4];
			$C = $tmpArr[5];
			$jsArr[] = '[\''.$time.'\','.$O.','.$C.','.$L.','.$H.']';
		}
		$jsStr = implode(',',$jsArr);
		echo '['.$jsStr.']';
		die();
	}

	public function information(){
		$db = $this->load->database('default',true);
		$table = 'news';
		$db->select("id,title,content,add_time")->from($table);
		$db->order_by('add_time DESC');
		$db->limit(20);
		$query =  $db->get();
        $artList = $query->result_array();
        $html = "";
        if(!empty($artList)) foreach($artList as $item){
        	// var_dump( $item);
        	$html .= '<div class="weui_media_box weui_media_text"><a data-toggle="collapse" href="#collapse'.$item['id'].'"><h4 class="weui_media_title">'.$item['title'].'</h4><p class="time">'.date('Y-m-d H:i',$item['add_time']).'</p><span class="r_ico"></span></a>';
        	$html .= '<div id="collapse'.$item['id'].'" class="collapse">'.$item['content'].'</div>';
        	$html .= "</div>";
        }
        // $html .= '<p class="more"><a href="/news">查看更多>></a></p>';
        echo $html;
        die;
	}

	public function rank(){
		$get		= $this->input->get();
		$page		= isset($get['page'])?$get['page']:"1";

		$table		= 'cfd_rank_yk';
		$admin_db	=  $this->load->database('admin',true);
		$sql		= "select date from cfd_rank_yk group by date order by date desc limit 10";
		$query		=  $admin_db->query($sql);
        $dateList	=  $query->result_array();

		$days		= $page-1;
		$date		= $dateList[$days]['date'];
		$admin_db->select()->from($table)->where(array("date"=>$date));
		$admin_db->order_by('yk DESC');
		$admin_db->limit(10);
		$query	=  $admin_db->get();
        $artList = $query->result_array();
        $html = "<table class='table table-striped'><tr><th>排名</th><th>用户名</th><th>用券量</th><th>盈利</th><th>话费奖励</th></tr>";
		$reward	=	array('1'=>300,'2'=>200,'3'=>100,'4'=>100,'5'=>50,'6'=>50,'7'=>50,'8'=>50,'9'=>50,'10'=>50);
		$i	=	1;
		$last_time	=	empty($artList)?"--":$artList[0]['datetime'];
        if(!empty($artList)) foreach($artList as $item){
			if($item['yk'] >0) {
				$html .= '<tr>';
				$html .= '<td>'.$i.'</td><td>'.$item['nickname'].'</td><td>'.$item['num'].'</td><td>￥'.bcadd($item['yk'],0,2).'</td><td>￥'.$reward[$i].'</td>';
				$html .= '</tr>';
				$i++;
			}
        }
		$html .= '</table>';
		$pre_page	=	$page-1;
		$next_page	=	$page+1; 
		$class		=	$page==1?"disabled":"";

		if($class=='disabled'){
			$html .= '<div style="text-align:center;">最近更新时间：'.$last_time.'</div><div class="page"><a  class="'.$class.'">上期</a>';
		}else{
			$html .= '<div style="text-align:center;">最近更新时间：'.$last_time.'</div><div class="page"><a href="javascript:clickPage('.$pre_page.')" class="'.$class.'">上期</a>';
		}
		
		$pageNum	=	count($dateList);
		$pageNum	=	$pageNum >=3?3:$pageNum;
		for($i=1;$i <= $pageNum;$i++){
			if($dateList[$i-1]['date']){
				$class	=	$page==$i?"disabled":"";
				$html	.= '<a href="javascript:clickPage('.$i.')" class="'.$class.'">'.date("m/d",strtotime($dateList[$i-1]['date'])).'</a>';
			}
		}

		$class		=	$page==$pageNum?"disabled":"";
		if($class=='disabled'){
			$html .= '<a class="'.$class.'">下期</a></div>';
		}else{
			$html .= '<a href="javascript:clickPage('.$next_page.')" class="'.$class.'">下期</a></div>';
		}

        echo $html;
        die;
	}

	public function userInfo(){
		$this->load->library('passPort');
        $this->passport->setPlatform($this->config->item('platform'));//设置平台
		$user_info = $this->passport->checkCookieAuthCode('','',true,false);
		$cny = (!empty($user_info))?$user_info['cny']:'0.00';
		$ticket = (!empty($user_info))?$user_info['ticket']:'0';
		$data = array(
			'logined' => (!empty($user_info))?1:0,
			'cny' => $cny,
			'ticket' => $ticket,
		);
		echo json_encode($data);
	}

	public function ticket(){
		$this->load->library('passPort');
        $this->passport->setPlatform($this->config->item('platform'));//设置平台
		$user_info = $this->passport->checkCookieAuthCode('','',true,false);
		
		$this->load->model('cfd_model');
	    $yk		= $this->cfd_model->getHistoryYk($user_info['uid'],'ticket');
		$data	= array(
			'yk' => $yk >0 ?$yk:0,
		);
		echo json_encode($data);
	}

}
